package com.handpay.zztong.hp;

import android.app.AlertDialog;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.handpay.framework.swiper.SwiperMode;
import com.handpay.framework.utils.ArithUtil;
import com.handpay.framework.utils.CommonUtils;
import com.handpay.zztong.hp.base.activity.ZZTongActivity;
import com.handpay.zztong.hp.bean.Account;
import com.handpay.zztong.hp.bean.ActionBar;
import com.handpay.zztong.hp.config.ZZTConfig;
import com.handpay.zztong.hp.config.ZZTConstant;
import com.handpay.zztong.hp.log.HPLog;
import com.handpay.zztong.hp.other.activity.ShowHtmlActivity;
import com.handpay.zztong.hp.protocol.BaseProtocolKey;
import com.handpay.zztong.hp.trans.activity.VPOSActivity;

import java.util.Hashtable;

/**
 * @author yhjia
 */
public class SuperTransferAccounts extends ZZTongActivity {

    /**
     * 收款人帐号
     */
    private EditText cardNo;

    /**
     * 收款人名称
     */
    private EditText receiverName;

    /**
     * 转账金额
     */
    private EditText transferAmount;

    /**
     * 是否同意转账说明
     */
    private CheckBox cbAgree;

    private static int REQUEST_CARD = 1;

    private int swiperMode = ZZTConstant.SWIPER_GOTO_VPOS;

    /***
     * 新增银联转账后的逻辑处理
     **/
    private LinearLayout ll_transacounts_head;//头部布局
    private TextView tv_uin;//银联转账
    private TextView tv_fasttrans;//快速转账
    private TextView tv_info;
    private LinearLayout ll_realename;
    private TextView label_amount;//转账实付金额

    private TextView tv_hint_trans;//转账注意事项
    private boolean isUinTrans = true;//是否是银联转账 默认： true
    private ImageView rightBar;
    private boolean isShowUinTransHead = false;//开关控制快速转账是否显示

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        setContentView(initLayoutID());
        super.onCreate(savedInstanceState);
        initViews();
        initListener();
    }

    private void initListener() {
        tv_fasttrans.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                showFastTransView();
            }
        });

        tv_uin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                showUniTransView();
            }
        });
    }

    protected int initLayoutID() {
        return R.layout.super_transfer_account;
    }

    @Override
    public ActionBar getActivityActionBar() {
        if (isUinTrans) {
            return new ActionBar(this.getString(R.string.super_unipay), true);
        } else {
            return new ActionBar(this.getString(R.string.super_transfer), true);
        }
    }

    protected void initViews() {
        final Intent intent = getIntent();
        Bundle bundle = intent.getExtras();
        mAction = bundle.getByte(ACTION);
        rightBar = new ImageView(this);
        rightBar.setImageResource(R.drawable.more);
        rightBar.setPadding(0, 0, 10, 0);
        rightBar.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                togoOtherActivity();
            }
        });
        myActionBar.addRightView(rightBar);

        cardNo = (EditText) findViewById(R.id.receiverCardNo);
        receiverName = (EditText) findViewById(R.id.receiverName);
        transferAmount = (EditText) findViewById(R.id.transferAmount);
        cbAgree = (CheckBox) findViewById(R.id.cbAgree);
        findViewById(R.id.btnAgreement).setOnClickListener(this);
        findViewById(R.id.nextButton).setOnClickListener(this);
        findViewById(R.id.swipeCard).setOnClickListener(this);

        //银联转账相关
        ll_transacounts_head = (LinearLayout) findViewById(R.id.ll_transacounts_head);
        if (!isShowUinTransHead) {
            ll_transacounts_head.setVisibility(View.GONE);
        }
        ll_realename = (LinearLayout) findViewById(R.id.ll_realename);
        tv_uin = (TextView) findViewById(R.id.tv_uin);
        tv_fasttrans = (TextView) findViewById(R.id.tv_fasttrans);
        tv_hint_trans = (TextView) findViewById(R.id.tv_hint_trans);
        label_amount = (TextView) findViewById(R.id.label_amount);
        tv_info = (TextView) findViewById(R.id.tv_info);
        if (mAction == ZZTongActivity.Action_CreditCardRepay) {
            myActionBar.setTitleText(R.string.repayment_Creditcard);
            isUinTrans = true;
            findViewById(R.id.agreeSuperLL).setVisibility(View.INVISIBLE);
            ((TextView) findViewById(R.id.btnAgreement)).setText(getResources().getString(R.string.repayment_explain));
            ((TextView) findViewById(R.id.label_amount)).setText(R.string.repayment_amount);
            ((Button) findViewById(R.id.nextButton)).setText(getResources().getString(R.string.Immediately_repayment));
            //hide head and transhint
            ll_transacounts_head.setVisibility(View.GONE);
            tv_hint_trans.setVisibility(View.GONE);
            ll_realename.setVisibility(View.GONE);
        }
    }

    private void showUniTransView() {
        isUinTrans = true;
        transferAmount.setText("");
        cardNo.setText("");
        ll_realename.setVisibility(View.GONE);
        tv_info.setVisibility(View.GONE);
        ll_transacounts_head.setBackgroundResource(R.drawable.tab_two);
        label_amount.setText(getString(R.string.uintrans_tip));
        tv_hint_trans.setVisibility(View.VISIBLE);
        myActionBar.refreshActionBar(new ActionBar(this.getString(R.string.super_unipay), true));
        myActionBar.addRightView(rightBar);
    }

    private void showFastTransView() {
        isUinTrans = false;
        ll_realename.setVisibility(View.VISIBLE);
        transferAmount.setText("");
        cardNo.setText("");
        receiverName.setText("");
        ll_transacounts_head.setBackgroundResource(R.drawable.tab_one);
        tv_hint_trans.setVisibility(View.GONE);
        label_amount.setText(getString(R.string.super_in_amount_tip));
        myActionBar.refreshActionBar(new ActionBar(this.getString(R.string.super_transfer), true));
        myActionBar.addRightView(rightBar);
    }

    @Override
    protected boolean isShownTabs() {
        return false;
    }

    /**
     * 立即转账
     *
     * @param v
     */
    public void transfer(View v) {
        String cardNum = cardNo.getText().toString();
        cardNum = cardNum.replace(" ", "");
        String name = receiverName.getText().toString();
        String amount = transferAmount.getText().toString();
        boolean isError = false;
        int errorMessage = 0;
        if (!isUinTrans) {
            if (TextUtils.isEmpty(name.trim())) {
                errorMessage = R.string.super_transfer_error_3;
                isError = true;
            } else if (!CommonUtils.isRealName(name)) {
                errorMessage = R.string.input_right_user_name_tip;
                isError = true;
            } else if (name.indexOf(" ") != -1) {
                errorMessage = R.string.input_right_user_name_tip;
                isError = true;
            }
        }
        if (TextUtils.isEmpty(cardNum)) {
            errorMessage = R.string.super_transfer_error_1;
            isError = true;
        } else if (!CommonUtils.isLegalCard(cardNum)) {
            isError = true;
            errorMessage = R.string.super_transfer_error_2;
        } else if (TextUtils.isEmpty(amount) || ".".equals(amount)) {
            errorMessage = R.string.super_transfer_error_4;
            isError = true;
        } else if (!cbAgree.isChecked()) {
            errorMessage = R.string.super_transfer_error_5;
            isError = true;
        }
        if (isError) {
            errorDialog(errorMessage);
            return;
        }
        gotoSuperTrans();
    }

    private void gotoSuperTrans() {
        if (requestCurrentLocation(true)) {
            swiperMode = ZZTConstant.SWIPER_GOTO_VPOS;
            setMode(SwiperMode.SUPER_TRANS, false, new Runnable() {
                @Override
                public void run() {
                    final Hashtable<String, Object> params = new Hashtable<String, Object>();

                    double money = Double.parseDouble(transferAmount.getText().toString());
                    HPLog.e("gotoSuperTrans", "action----:" + mAction);
                    if (mAction == ZZTongActivity.Action_CreditCardRepay) {
//                        params.put(ZZTongActivity.ACTION, Action_CreditCardRepay);
                        params.put(ZZTongActivity.ACTION, Action_SuperUniTrans);
                        params.put(ZZTongActivity.ACTION_FROM, ZZTongActivity.Action_FROM_CREDIT);
                    } else {
                        if (!isUinTrans) {
                            params.put(ZZTongActivity.ACTION, Action_SuperTransfer);
                        } else {
                            params.put(ZZTongActivity.ACTION, Action_SuperUniTrans);
                            params.put(ZZTongActivity.ACTION_FROM, ZZTongActivity.Action_FROM_UNI_TRANS);
                        }
                    }
                    params.put(VPOSActivity.Transfer_Amount_Key, ArithUtil.mul(money, 100d));
                    Account cardInAccount = new Account();
                    String cardNum = cardNo.getText().toString();
                    cardNum = cardNum.replace(" ", "");
                    cardInAccount.setCardPlainNo(cardNum);
                    cardInAccount.setCardName(receiverName.getText().toString().trim());
                    cardInAccount.setCardNo(CommonUtils.formatCard(cardNo.getText().toString()));
                    params.put(VPOSActivity.Transfer_To_Accounts_Key, cardInAccount);
                    startActivity(SuperTransferAccounts.this, VPOSActivity.class, params);
                }
            });
        }
    }

    private void getPan() {
        Log.i("result", "getPan");
        setMode(SwiperMode.SUPER_TRANS, true, new Runnable() {
            @Override
            public void run() {
                Intent intent = new Intent(SuperTransferAccounts.this, SwipeCard.class);
                startActivityForResult(intent, REQUEST_CARD);
            }
        });
    }

    private void errorDialog(int messageId) {
        new AlertDialog.Builder(this)
                .setTitle(R.string.tip)
                .setIcon(android.R.drawable.ic_dialog_info)
                .setCancelable(false)
                .setPositiveButton(android.R.string.ok, null)
                .setMessage(messageId)
                .show();
    }

    @Override
    public void onClick(View v) {
        int i = v.getId();
        if (i == R.id.nextButton) {
            transfer(v);
        } else if (i == R.id.btnAgreement) {
            Intent intent = new Intent(this, ShowHtmlActivity.class);
            if (isUinTrans) {
                intent.putExtra(ShowHtmlActivity.ShowHtml_Title_Key, getString(R.string.uin_transfer_agreement));
                intent.putExtra(ShowHtmlActivity.ShowHtml_Html_Path_Key, getResources().getString(R.string.unipay_transfer_help_url));
            } else {
                intent.putExtra(ShowHtmlActivity.ShowHtml_Title_Key, getString(R.string.super_transfer_agreement));
                intent.putExtra(ShowHtmlActivity.ShowHtml_Html_Path_Key, ZZTConfig.HPZZT_SUPERTRANS_URL);
            }
            this.startActivity(intent);
        } else if (R.id.swipeCard == i) {
            gotoSwiperCard();
        }
        super.onClick(v);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (REQUEST_CARD == requestCode) {
            if (RESULT_OK == resultCode && null != data) {
                cardNo.setText(data.getStringExtra(BaseProtocolKey.ACCOUNT));
            }
        } else {
            super.onActivityResult(requestCode, resultCode, data);
        }
    }

    @Override
    public void onSwiperPlugOff() {
        // 回到HPFunction界面
        onFunctionTab(null);
    }

    @Override
    public void goToVPos() {
        super.goToVPos();

        switch (swiperMode) {
            case ZZTConstant.SWIPER_GOTO_VPOS:
                gotoSuperTrans();
                break;
            case ZZTConstant.SWIPER_GOTO_SWIPERCARD:
                gotoSwiperCard();
                break;
            case ZZTConstant.SWIPER_GOTO_OTHER:
                togoOtherActivity();
                break;
            default:
                break;
        }
    }

    @Override
    public void onConnectSuccess() {
        super.onConnectSuccess();
        Log.i("result", "onConnectSuccess");

    }

    private void gotoSwiperCard() {
        swiperMode = ZZTConstant.SWIPER_GOTO_SWIPERCARD;
        setMode(SwiperMode.SUPER_TRANS, true, new Runnable() {
            @Override
            public void run() {
                Intent intent = new Intent(SuperTransferAccounts.this, SwipeCard.class);
                startActivityForResult(intent, REQUEST_CARD);
            }
        });
    }

    private void togoOtherActivity() {
        swiperMode = ZZTConstant.SWIPER_GOTO_OTHER;
        if (requestCurrentLocation(true)) {
//			setMode(SwiperMode.SUPER_TRANS, false, new Runnable() {
//				@Override
//				public void run() {
            Intent i = new Intent(SuperTransferAccounts.this, FastTransferActivity.class);
            if (mAction == Action_CreditCardRepay) {
                i.putExtra(ACTION, Action_CreditCardRepay);
            } else {
                i.putExtra(ACTION, Action_SuperTransfer);
                if (!isUinTrans) {
                    i.putExtra(ZZTongActivity.ACTION, Action_SuperTransfer);
                } else {
                    i.putExtra(ZZTongActivity.ACTION, Action_SuperUniTrans);
                }
            }
            SuperTransferAccounts.this.startActivity(i);
//				}
//			});
        }
    }
}
